package com.tiancheng.onecode.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tiancheng.onecode.entity.MemberOrder;
import com.tiancheng.onecode.entity.MemberOrderRefund;
import com.tiancheng.onecode.entity.MemberSubOrder;
import com.tiancheng.onecode.entity.MerchantVoiceDevice;
import com.tiancheng.onecode.enums.DeviceAgreementEnums;
import com.tiancheng.onecode.enums.OrderStatusEnum;
import com.tiancheng.onecode.exception.Asserts;
import com.tiancheng.onecode.mapper.MerchantVoiceDeviceMapper;
import com.tiancheng.onecode.model.request.admin.AddMerchantVoiceDeviceReq;
import com.tiancheng.onecode.model.response.api.QueryDeviceListRes;
import com.tiancheng.onecode.model.response.api.QueryDeviceTypeRes;
import com.tiancheng.onecode.model.thrid.AddDeviceReq;
import com.tiancheng.onecode.model.thrid.DeviceNoticeReq;
import com.tiancheng.onecode.service.IMerchantVoiceDeviceService;
import com.tiancheng.onecode.utils.AmountUtil;
import com.tiancheng.onecode.utils.DeviceCenterUtils;
import com.tiancheng.onecode.utils.IdWorkerUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商户语音播报设备service 实现
 */
@Slf4j
@Service
public class MerchantVoiceDeviceServiceImpl extends ServiceImpl<MerchantVoiceDeviceMapper, MerchantVoiceDevice> implements IMerchantVoiceDeviceService {

    @Autowired
    private DeviceCenterUtils deviceCenterUtils;
    @Resource
    private TransactionTemplate transactionTemplate;

    @Override
    public MerchantVoiceDevice addDevice(AddMerchantVoiceDeviceReq params) {
        List<MerchantVoiceDevice> devices = this.list(new LambdaQueryWrapper<MerchantVoiceDevice>().eq(MerchantVoiceDevice::getDeviceNo, params.getDeviceNo()));
        if (CollectionUtils.isNotEmpty(devices)) {
            Asserts.isTrue(devices.get(0).getPlatformMerchantId().equals(params.getPlatformMerchantId()), "该设备以绑定到其他商户，请先完成解绑！");
            return devices.get(0);
        }
        // 调用云音响系统绑定设备
        AddDeviceReq addDeviceReq = new AddDeviceReq();
        addDeviceReq.setBusinessUnitID(params.getPlatformMerchantId().toString());
        addDeviceReq.setType(params.getDeviceType());
        addDeviceReq.setName(params.getDeviceName());
        addDeviceReq.setDeviceNo(params.getDeviceNo());
        deviceCenterUtils.addDevice(addDeviceReq);
        clearAndInsert(params.getPlatformMerchantId());
        return null;
    }

    /**
     * 清空商户的设备信息，再次查询并保存
     *
     * @param platformMerchantId 平台商户id
     */
    private void clearAndInsert(final Long platformMerchantId) {
        this.remove(new LambdaQueryWrapper<MerchantVoiceDevice>().eq(MerchantVoiceDevice::getPlatformMerchantId, platformMerchantId));
        List<QueryDeviceListRes> queryDeviceListRes = deviceCenterUtils.queryDeviceList(platformMerchantId);
        if (CollectionUtils.isNotEmpty(queryDeviceListRes)) {
            // 清空
            final Boolean result = transactionTemplate.execute(transactionStatus -> {
                try {
                    List<MerchantVoiceDevice> devices = queryDeviceListRes.stream().filter(d -> !d.getStatus().equalsIgnoreCase("delete")).map(d -> {
                        MerchantVoiceDevice voiceDevice = new MerchantVoiceDevice();
                        voiceDevice.setPlatformMerchantId(platformMerchantId);
                        voiceDevice.setAgreement(DeviceAgreementEnums.CLOUD_SPEAKER.getCode());
                        voiceDevice.setDeviceType(d.getDeviceType());
                        voiceDevice.setDeviceName(d.getDeviceName());
                        voiceDevice.setDeviceNo(d.getDeviceNo());
                        voiceDevice.setDeviceStatus(0);
                        voiceDevice.setCreatedDt(LocalDateTime.now());
                        voiceDevice.setLastUpdDt(LocalDateTime.now());
                        voiceDevice.setDeviceId(d.getDeviceId());
                        return voiceDevice;
                    }).toList();
                    this.saveBatch(devices);
                    return true;
                } catch (Exception e) {
                    transactionStatus.setRollbackOnly();
                    throw e;
                }
            });
            Asserts.isTrue(null != result && result, "操作失败!");
        }
    }

    @Override
    public List<MerchantVoiceDevice> queryByPlatformMerchantId(Long platformMerchantId, boolean queryOnLineStatus) {
        List<MerchantVoiceDevice> list = this.list(new LambdaQueryWrapper<MerchantVoiceDevice>().eq(MerchantVoiceDevice::getPlatformMerchantId, platformMerchantId)
                .eq(MerchantVoiceDevice::getDeviceStatus, 0).orderByAsc(MerchantVoiceDevice::getLastUpdDt));
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        if (!queryOnLineStatus) {
            return list;
        }
        List<QueryDeviceListRes> queryDeviceListRes = deviceCenterUtils.queryDeviceList(platformMerchantId);
        if (CollectionUtils.isNotEmpty(queryDeviceListRes)) {
            for (QueryDeviceListRes device : queryDeviceListRes) {
                list.stream().filter(l -> l.getDeviceId().equals(device.getDeviceId())).forEach(l -> {
                    if (device.getOnlineStatus().equals("Online")) {
                        l.setOnlineStatus(1);// 在线
                    } else {
                        l.setOnlineStatus(0);// 离线
                    }
                });
            }
        }
        return list;
    }

    @Override
    public void remove(Long id) {
        MerchantVoiceDevice one = this.getById(id);
        Asserts.isNotNull(one, "未查询到设备！");
        // TODO 调用云音响系统删除设备
        deviceCenterUtils.removeDevice(one.getDeviceId());
        clearAndInsert(one.getPlatformMerchantId());
    }


    @Override
    public List<QueryDeviceTypeRes> queryDeviceType(Long platformMerchantId) {
        // TODO 后面如果有多重协议的音响后修改
        return deviceCenterUtils.queryDeviceType();
    }

    @Override
    public void payNotice(Long platformMerchantId, String merchantName, int amount) {
        try {
            List<MerchantVoiceDevice> devices = queryByPlatformMerchantId(platformMerchantId,false);
            if (CollectionUtils.isEmpty(devices)) {
                log.warn("商户【{}】未设置语音播报设备！", merchantName);
                return;
            }
            devices.stream().filter(d -> d.getAgreement().equals(DeviceAgreementEnums.CLOUD_SPEAKER.getCode())).forEach(d -> {
                DeviceNoticeReq notice = new DeviceNoticeReq();
                //0：包含金额；1：普通文本
                notice.setBusinessUnitID(platformMerchantId.toString());
                notice.setMsgFormatType("0");
                notice.setMsg("收款到账" + AmountUtil.getYUAN(amount) + "元");
                notice.setMsgId(IdWorkerUtils.getInstance().buildPartNumber());
                deviceCenterUtils.notice(notice);
            });
        } catch (Exception e) {
            log.error("推送消息到云音响异常:", e);
        }
    }
}
